﻿using System;
using System.Collections.Generic;
using System.Text;
using  System.Collections;
using SmartSiteManagementSystem.IServices;
using SmartSiteManagementSystem.IRepository.Admin;
using SmartSiteManagementSystem.Models.Admin;
using System.Linq;

namespace SmartSiteManagementSystem.Services
{
    public class AdminService : IAdminService
    {

        private readonly IAdminUserInfoRepository _adminnUserInfoRepository;
        private readonly IAdminMenuInfoRepository _adminMenuInfoRepository;
        private readonly IAdminGroupInfoRepository _adminGroupInfoRepository;
        private readonly IAdminUserGroupMenuInfoRepository _adminUserGroupMenuInfoRepository;
        private readonly IAdminGroupBtnRelInfoRepository _adminGroupBtnRelInfoRepository;
        private readonly IAdminPageBtnInfoRepository _adminPageBtnInfoRepository;
        private readonly IAdminUserGroupRelationInfoRepository _adminUserGroupRelationInfoRepository;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="adminUserInfoRepository"></param>
        public AdminService(IAdminUserInfoRepository adminUserInfoRepository
            , IAdminMenuInfoRepository adminMenuInfoRepository
            , IAdminGroupInfoRepository adminGroupInfoRepository
            ,IAdminUserGroupMenuInfoRepository adminUserGroupMenuInfoRepository
            , IAdminGroupBtnRelInfoRepository adminGroupBtnRelInfoRepository
            , IAdminPageBtnInfoRepository adminPageBtnInfoRepository
            , IAdminUserGroupRelationInfoRepository adminUserGroupRelationInfoRepository)
        {
            _adminnUserInfoRepository = adminUserInfoRepository;
            _adminMenuInfoRepository = adminMenuInfoRepository;
            _adminGroupInfoRepository = adminGroupInfoRepository;
            _adminUserGroupMenuInfoRepository = adminUserGroupMenuInfoRepository;
            _adminGroupBtnRelInfoRepository = adminGroupBtnRelInfoRepository;
            _adminPageBtnInfoRepository = adminPageBtnInfoRepository;
            _adminUserGroupRelationInfoRepository=adminUserGroupRelationInfoRepository;
    }

        #region AdminUserInfo
        /// <summary>
        /// 
        /// </summary>
        /// <param name="adminUserId"></param>
        /// <returns></returns>
        public AdminUserInfo GetAdminUserInfoByUserId(Int32 adminUserId)
        {
            Hashtable param = new Hashtable();
            param.Add("user_id", adminUserId);

            return _adminnUserInfoRepository.Get(param);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public int GetAdminUserInfoCount(Hashtable param)
        {
           return _adminnUserInfoRepository.GetCount(param);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <param name="orderBy"></param>
        /// <param name="first"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        public IList<AdminUserInfo> GetAdminUserInfoList(Hashtable param, string orderBy, int first, int rows)
        {
            IList<AdminUserInfo> list =_adminnUserInfoRepository.GetList(param, orderBy, first, rows);
            if (list != null && list.Count > 0)
            {
                //TAdminGroupBLL adminGroupBll = new TAdminGroupBLL();
                //TAdminUserGroupRelationBLL adminUserGroupRelationBll = new TAdminUserGroupRelationBLL();
                IList<AdminGroupInfo> adminGroupList = new List<AdminGroupInfo>();
                IList<AdminUserGroupRelationInfo> augrList = new List<AdminUserGroupRelationInfo>();
                List<int> ids = new List<int>();
                list.ToList().ForEach(item =>
                {
                    Hashtable tempparam = new Hashtable();
                    tempparam.Add("is_deleted_stop", 0);//正常 0 false
                    tempparam.Add("admin_user_id", item.AdminUserId);
                    augrList = _adminUserGroupRelationInfoRepository.GetList(tempparam);
                    if (augrList != null && augrList.Count > 0)
                    {
                      
                        ids = (from augrItem in augrList select augrItem.AdminUserGroupId).ToList();
                        item.RoleNames = GetGroupNames(ids);

                    }
                });
            }
            return list;
        }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>返回：该条数据的主键Id</returns>
        public int InsertAdminUserInfo(AdminUserInfo obj)
        {
            return _adminnUserInfoRepository.Insert(obj);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool UpdateAdminUserInfo(AdminUserInfo obj)
        {
            return _adminnUserInfoRepository.Update(obj);
        }

        /// <summary>
        /// 用户名查找用户对象
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public AdminUserInfo GetByUsername(string username)
        {
            Hashtable p = new Hashtable();
            p.Add("user_name", username);
            return _adminnUserInfoRepository.Get(p);

        }

        /// <summary>
        /// 获取登录管理员权限数据（按钮类型的权限）
        /// </summary>
        /// <param name="adminUserid"></param>
        /// <returns></returns>
        public Hashtable GetAdminUserInfoRightList(int adminUserId)
        {
            Hashtable ht = new Hashtable();
            Hashtable ght = new Hashtable();
            Hashtable param = new Hashtable();
            param.Add("admin_user_id", adminUserId);
            IList<AdminUserGroupRelationInfo> relationList = _adminUserGroupRelationInfoRepository.GetList(param);
            AdminGroupInfo AdminUserGroupObj = null;
            IList<AdminUserGroupMenuInfo> list_groupMenuInfo = null;
            foreach (AdminUserGroupRelationInfo item in relationList)
            {

                AdminUserGroupObj = GetAdminGroupById(item.AdminUserGroupId);
                if (AdminUserGroupObj != null && AdminUserGroupObj.StopFlag == false && AdminUserGroupObj.DeleteFlag == false)
                {
                    ght.Clear();
                    ght["group_id"] = item.AdminUserGroupId;
                    list_groupMenuInfo = _adminUserGroupMenuInfoRepository.GetList(param, null, 0, 10000);
                    foreach (AdminUserGroupMenuInfo GroupMenuInfo in list_groupMenuInfo)
                    {
                        ht = addRightList(GroupMenuInfo.AdminMenuInfo, item.AdminUserGroupId, ht);

                    }
                }
            }

            return ht;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private  string getAbsolutePath(string url)
        {
            if (string.IsNullOrEmpty(url))
                return null;
            if (url.LastIndexOf("?") > 0)
                return url.Substring(0, url.LastIndexOf("?"));
            return url;
        }

        /// <summary>
        /// 将按钮类型的权限加入权限列表
        /// </summary>
        /// <param name="adminMenuInfo"></param>
        /// <param name="ht"></param>
        /// <returns></returns>
        private Hashtable addRightList(AdminMenuInfo adminMenuInfo, int AdminUserGroupId, Hashtable ht)
        {
            if (ht == null)
            {
                ht = new Hashtable();
            }

            //把主目录放入权限表
            if (!string.IsNullOrEmpty(adminMenuInfo.Url) && ht[getAbsolutePath(adminMenuInfo.Url.ToLower())] == null)
            {
                ht[adminMenuInfo.Url.ToLower()] = 0;//0表示菜单
            }
            //将关联按钮的url放入权限表

            string[] stringSeparators = new string[] { "|&&|" };
            AdminPageBtnInfo BtnControlObj = null;

            Hashtable param = new Hashtable();
            param.Add("admin_user_groupid", AdminUserGroupId);
            if (adminMenuInfo.AdminMenuId > 0)
            {
                param.Add("admin_menuid", adminMenuInfo.AdminMenuId);
            }

            IList<AdminGroupBtnRelInfo> GroupBtnRelList = _adminGroupBtnRelInfoRepository.GetList(param, string.Empty, 0, _adminGroupBtnRelInfoRepository.GetCount(param));
            int k = 0;
            Hashtable bht = new Hashtable();
            string temp = string.Empty;
            foreach (AdminGroupBtnRelInfo item in GroupBtnRelList)
            {
                k++;
                bht.Clear();
                bht.Add("btn_id", item.BtnId);
                temp = string.Empty;
                BtnControlObj = _adminPageBtnInfoRepository.Get(bht);
                //按钮管理
                if (BtnControlObj != null && BtnControlObj.BtnType == 0 && !string.IsNullOrEmpty(BtnControlObj.RelUrl))
                {

                    string[] relevanceUrlArr = BtnControlObj.RelUrl.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
                    if (relevanceUrlArr != null && relevanceUrlArr.Length >= 1)
                    {
                        for (int i = 0; i < relevanceUrlArr.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(relevanceUrlArr[i]) && ht[relevanceUrlArr[i].ToLower()] == null)
                            {
                                ht[relevanceUrlArr[i].ToLower()] = adminMenuInfo.Url + "," + BtnControlObj.ClientId;//菜单路径+clientid给按钮
                            }
                        }
                    }
                }
                //筛选条件管理
                if (BtnControlObj != null && BtnControlObj.BtnType == 1)
                {
                    temp = BtnControlObj.ClientId + k.ToString();
                    ht[temp] = adminMenuInfo.Url + "," + BtnControlObj.ClientId;//菜单路径+clientid给按钮
                }
            }
            return ht;
        }
        #endregion
        #region AdminMenuInfo

        public AdminMenuInfo GetAdminMenuInfoById(Int32 adminMenuId)
        {

            Hashtable param = new Hashtable();
            param.Add("menu_id", adminMenuId);
            return _adminMenuInfoRepository.Get(param);
        }

        /// <summary>
        /// 根据管理员Id获取其导航菜单列表(自动判断该帐号是否为系统管理员，是则赋予所有导航菜单权限)【排除已经禁用角色的所有权限】
        /// </summary>
        /// <param name="adminUserId"></param>
        /// <param name="userType"></param>
        /// <returns></returns>
        public IList<AdminMenuInfo> GetNavigationMenu(int adminUserId, int userType)
        {
            IList<AdminMenuInfo> List = null;
            Hashtable param = new Hashtable();
            if (userType != 2)
            {
                param.Add("AdminUserId", adminUserId);
            }
            List = _adminMenuInfoRepository.GetList(param);

            return List;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="menuList"></param>
        /// <returns></returns>
        public IList<Hashtable> GetTree(IList<AdminMenuInfo> menuList)
        {
            if (menuList == null) return null;

            IList<Hashtable> nodes = new List<Hashtable>();
            foreach (var item in menuList.Where(p => p.ParentId == 0 && p.ShowFlag == true).OrderBy(p => p.SortOrder))
            {
                var ht = GetNode(item);
                ht["children"] = GetChildrenList(menuList, ht, item.AdminMenuId);
                if (ht["children"] != null)
                {
                    ht["state"] = "close";
                }
                nodes.Add(ht);
            }

            return nodes;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public Hashtable GetNode(AdminMenuInfo info)
        {
            Hashtable ht = new Hashtable();
            ht["id"] = info.AdminMenuId;
            ht["text"] = info.MenuName;
            //ht["checked"] = "false";

            if (info.IsParent)
            {
                //ht["state"] = "closed";
            }
            else
            {
                ht["attributes"] = new
                {
                    url = info.Url
                };

            }

            return ht;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="menuList"></param>
        /// <param name="parentNode"></param>
        /// <param name="pId"></param>
        /// <returns></returns>
        public IList<Hashtable> GetChildrenList(IEnumerable<AdminMenuInfo> menuList, Hashtable parentNode, int pId)
        {
            IList<Hashtable> nodes = new List<Hashtable>();
            foreach (var item in menuList.Where(p => p.ParentId == pId && p.ShowFlag == true).OrderBy(p => p.SortOrder))
            {
                var ht = GetNode(item);
                nodes.Add(ht);
                ht["children"] = GetChildrenList(menuList, ht, item.AdminMenuId);
                if (ht["children"] != null)
                {
                    ht["state"] = "close";
                }
                if (item.IsParent)
                {
                    GetChildrenList(menuList.Where(p => p.ParentId == item.AdminMenuId), ht, item.AdminMenuId);
                }
            }
            return nodes;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IList<AdminMenuInfo> GetAllMenuInfoList()
        {
            Hashtable param = new Hashtable();
            IList<AdminMenuInfo> list = _adminMenuInfoRepository.GetList(param, "sort_order asc", 0, 5000);
            return list;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <param name="orderBy"></param>
        /// <param name="first"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        public IList<AdminMenuInfo> GetAdminMenuInfoListByParam(Hashtable param, string orderBy, int first, int rows)
        {
           return _adminMenuInfoRepository.GetList(param, orderBy, first, rows);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool UpdateAdminMenuInfo(AdminMenuInfo obj)
        {
            return _adminMenuInfoRepository.Update(obj);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int InsertAdminMenuInfo(AdminMenuInfo obj)
        {
            return _adminMenuInfoRepository.Insert(obj);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="adminMenuId"></param>
        /// <returns></returns>
        public bool DeleteMenuAndRelData(int adminMenuId)
        {
            return _adminMenuInfoRepository.DeleteMenuAndRelData(adminMenuId);
        }

        #endregion

        #region AdminGroup

        public string GetGroupNames(List<int> ids)
        {
            string groupNames = "";
            if (ids != null && ids.Count > 0)
            {
                Hashtable param = new Hashtable();
                param.Add("Ids", string.Join(",", ids));
                param.Add("DeleteFlag", 0);//正常 0 false
                IList<AdminGroupInfo> list =_adminGroupInfoRepository.GetList(param, "", 0, 3000);
                if (list != null && list.Count > 0)
                {
                    groupNames = string.Join(",", list.Select(m => m.AdminUserGroupName).ToArray());
                }
            }
            return groupNames;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public int GetAdminGroupCount(Hashtable param)
        {
            return _adminGroupInfoRepository.GetCount(param);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <param name="orderBy"></param>
        /// <param name="first"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        public IList<AdminGroupInfo> GetAdminGroupList(Hashtable param, string orderBy, int first, int rows)
        {
            return _adminGroupInfoRepository.GetList(param, orderBy, first, rows);
        }

        public AdminGroupInfo GetAdminGroupById(int groupId)
        {
            Hashtable param = new Hashtable();
            param.Add("group_id", groupId);
            return _adminGroupInfoRepository.Get(param);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int InsertAdminUserGroup(AdminGroupInfo obj)
        {
            return _adminGroupInfoRepository.Insert(obj);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool UpdateAdminUserGroup(AdminGroupInfo obj)
        {
            return _adminGroupInfoRepository.Update(obj);
        }





        #endregion

        #region AdminUserGroupMenuInfo
        /// <summary>
        /// 提取某个用户组ID所属的所有分类的list
        /// </summary>
        /// <returns></returns>
        public IList<AdminUserGroupMenuInfo> GetAllAdminUserGroupMenuListByadminUserId(int adminUserGroupId)
        {
            Hashtable param = new Hashtable();

            param.Add("group_id", adminUserGroupId);

            return _adminUserGroupMenuInfoRepository.GetList(param, null, 0, 10000);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="adminUserGroupId"></param>
        /// <param name="ids"></param>
        public void UpdateAdminUserGroupMenu(int adminUserGroupId, string ids)
        {
            if (ids != null)
            {
                string[] idArr = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                AdminUserGroupMenuInfo maugmInfo;
                IList<AdminUserGroupMenuInfo> maugmList = new List<AdminUserGroupMenuInfo>();
                AdminGroupBtnRelInfo mgbrInfo;
                IList<AdminGroupBtnRelInfo> mgbrList = new List<AdminGroupBtnRelInfo>();
                int pid = 0;
                AdminMenuInfo menuItemObj = null;
                List<int> idList = new List<int>();

                foreach (var item in idArr)
                {
                    int id = Convert.ToInt32(item);
                    if (id < 100000)//菜单，100000为分界线
                    {
                        menuItemObj = GetAdminMenuInfoById(id);
                        if (menuItemObj != null) pid = menuItemObj.ParentId;
                        if (!idList.Contains(pid) && pid > 0)
                            idList.Add(pid);
                        if (!idList.Contains(id))
                            idList.Add(id);
                    }
                    else
                    {
                        idList.Add(id);
                    }
                }
                foreach (int id in idList)
                {

                    if (id < 100000)//菜单，100000为分界线
                    {
                        maugmInfo = new AdminUserGroupMenuInfo();
                        maugmInfo.AdminMenuId = id;
                        maugmInfo.AdminUserGroupId = adminUserGroupId;
                        maugmList.Add(maugmInfo);
                    }
                    else if (id % 100000 == 0)//能被100000整除的为表里面的数据，否则为构造出来的，如“按钮”，“筛选条件”两个父级分类，只存储其下的子分类
                    {
                        mgbrInfo = new AdminGroupBtnRelInfo();
                        mgbrInfo.AdminUserGroupId = adminUserGroupId;
                        mgbrInfo.BtnId = id / 100000;
                        mgbrList.Add(mgbrInfo);
                    }
                }
                _adminUserGroupMenuInfoRepository.UpdateGroupMenu(adminUserGroupId, maugmList, mgbrList);
            }
        }
        #endregion

        #region AdminGroupBtnRelInfo
        /// <summary>
        /// 提取数据
        /// </summary>
        /// <param name="param">可选参数为：</param>
        /// <param name="orderBy">排序方式:默认为“RelId asc”</param>
        /// <param name="first">起始记录：从0开始</param>
        /// <param name="rows">提取的条数</param>
        /// <returns></returns>
        public IList<AdminGroupBtnRelInfo> GetAdminGroupBtnRelInfoList(Hashtable param, string orderBy, int first, int rows)
        {
            return _adminGroupBtnRelInfoRepository.GetList(param, orderBy, first, rows);
        }

        #endregion

        #region AdminPageBtnInfo
        /// <summary>
        /// 
        /// </summary>
        /// <param name="btnId"></param>
        /// <param name="relList"></param>
        /// <param name="btnName"></param>
        /// <param name="btnClientId"></param>
        /// <param name="btnSortNo"></param>
        /// <param name="btnType"></param>
        /// <param name="adminMenuId"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public bool UpdateAdminPageBtnInfo(int[] btnId, string[] relList, string[] btnName, string[] btnClientId, int[] btnSortNo, int[] btnType, int adminMenuId, string userName)
        {
            Hashtable p;
            AdminPageBtnInfo mbcInfo;
            IList<AdminPageBtnInfo> mbcList = new List<AdminPageBtnInfo>();
            IList<Hashtable> btnList = new List<Hashtable>();

            for (int i = 0; i < btnId.Length; i++)//循环添加现在的
            {
                if (string.IsNullOrEmpty(btnName[i]) || string.IsNullOrEmpty(btnClientId[i])) continue;//如果名称为空，或者页面id为空，则不执行，继续下一条
                if (btnId[i] == 0)//添加
                {
                    mbcInfo = new AdminPageBtnInfo();
                    mbcInfo.AdminMenuId = adminMenuId;
                    mbcInfo.BtnName = btnName[i];
                    mbcInfo.BtnType = btnType[i];
                    mbcInfo.SortNo = btnSortNo[i];
                    mbcInfo.ClientId = btnClientId[i];
                    mbcInfo.RelUrl = relList[i];
                    mbcInfo.CreateMan = userName;
                    mbcList.Add(mbcInfo);
                }
                else//修改
                {
                    p = new Hashtable();
                    p["W_Id"] = btnId[i];
                    p["AdminMenuId"] = adminMenuId;
                    p["BtnName"] = btnName[i];
                    p["BtnType"] = btnType[i];
                    p["SortNo"] = btnSortNo[i];
                    p["ClientId"] = btnClientId[i];
                    p["RelUrl"] = relList[i];
                    btnList.Add(p);
                }
            }
            return _adminPageBtnInfoRepository.UpdateByTran(adminMenuId, mbcList, btnList);
        }


        /// <summary>
        /// /
        /// </summary>
        /// <param name="adminMenuId"></param>
        /// <returns></returns>
        public IList<AdminPageBtnInfo> GetAdminPageBtnInfoList(int adminMenuId)
        {
            Hashtable param = new Hashtable();
            param.Add("admin_menu_id", adminMenuId);
            return _adminPageBtnInfoRepository.GetList(param,"",0,10000);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <param name="orderBy"></param>
        /// <param name="first"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        public IList<AdminPageBtnInfo> GetAdminPageBtnInfoListByParam(Hashtable param, string orderBy, int first, int rows)
        {
            //return _adminPageBtnInfoRepository.GetList(param);
            return _adminPageBtnInfoRepository.GetList(param, "", 0, 10000);
        }

        #endregion


        #region AdminUserGroupRelationInfo

        /// <summary>
        /// 用户是否属于某个角色
        /// </summary>
        /// <returns></returns>
        public  bool IsExistAdminUserGroupRelation(int admingroupId, int adminUsrId)
        {
            if (admingroupId > 0 && adminUsrId > 0)
            {
                Hashtable param = new Hashtable();
                param.Add("admin_user_id", adminUsrId);
                param.Add("user_group_id", admingroupId);
                return _adminUserGroupRelationInfoRepository.GetCount(param) > 0 ? true : false;
            }
            return false;
        }



        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="adminUserId">adminUserId</param>
        /// <returns>返回</returns>
        public bool DeleteAdminUserGroupRelationInfo(int adminUserId)
        {
            Hashtable param = new Hashtable();
            param.Add("admin_user_id", adminUserId);
            return _adminUserGroupRelationInfoRepository.Delete(param);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public int InsertAdminUserGroupRelationInfo(AdminUserGroupRelationInfo info)
        {
           return _adminUserGroupRelationInfoRepository.Insert(info);
        }
        #endregion
    }
}
